package com.hugoo.form.slt;

import com.hugoo.ajxl.util.ExcelUtils;
import com.hugoo.core.Conf;
import com.hugoo.core.db.HSF;
import com.hugoo.core.db.mo.Record;
import com.hugoo.core.db.mo.RecordSet;
import com.hugoo.core.slt.AcFwd;
import com.hugoo.core.slt.Action;
import com.hugoo.core.util.TL;
import com.hugoo.form.buzz.CacheProc;
import com.hugoo.form.buzz.XTreeBuzz;
import com.hugoo.form.sql.SqlProc;
import com.hugoo.form.xo.XForm;
import com.hugoo.form.xo.XHandle;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Lovelock.Chan
 */
public class JsonAction extends Action {

    @Override
    public AcFwd exec(HttpServletRequest request, HttpServletResponse response) {
        String px[] = _sid.split("-"), p;
        if (px.length != 2) {
            log.error("传入的请求指数值节点错误,SID无法正常识别->" + _sid);
            return null;
        }
        _sid = px[0];
        procJson(request, response, px[1]);
        return null;
    }

    public AcFwd lists(HttpServletRequest request, HttpServletResponse response) {
        procJson(request, response, null);
        return null;
    }

    private void procJson(HttpServletRequest request, HttpServletResponse response, String xHandle) {
        if (checkPara(request, response)) {
            int ps = TL.parseInt(request.getParameter("rows"), 20);
            int cp = TL.parseInt(request.getParameter("page"), 1);
            String sort = request.getParameter("sort");
            String __dsm__ = request.getParameter("__dsm__");
            String tpl = null, order = null;
            //
            Map mx = this.parsePara(request);
            log.info("传入的参数集合如下：\n\t" + mx);
            ///////////////////////////////////////
            XForm xf = Conf.getXForm(_sid);
            XHandle lhandle;
            if (TL.isEmpty(xHandle)) {
                lhandle = xf.getListHandle();
            } else {
                lhandle = xf.getXHandle(xHandle);
            }
            if (lhandle == null) {
                log.error("未找到需要处理的Handle->" + xHandle);
                return;
            }
            SqlProc sp = new SqlProc(lhandle);
            String sql = sp.crtSql(mx);
            //处理排序问题
            if (TL.isNotEmpty(sort)) {
                order = request.getParameter("order");
                order = "order by " + sort + " " + order;
            }
            //处理SQL语句问题
            if (TL.isNotEmpty(order) || TL.isNotEmpty(tpl)) {
                sql = "select * from (" + sql + ") ";
                if (TL.isNotEmpty(tpl)) {
                    sql += " where " + tpl;
                }
                if (TL.isNotEmpty(order)) {
                    sql += " " + order;
                }
            }
            if (TL.isNotEmpty(__dsm__)) {
                if ("XLST".equalsIgnoreCase(__dsm__)) {
                    RecordSet<Record> rs = HSF.query(lhandle.getDbl(), sql, 20000, 1);
                    String xslt = lhandle.getXslt();
                    if (TL.isEmpty(xslt)) {
                        log.info("无效的XLS模板配置！");
                        super.writeDataToClient(response, "配置的XLS导出文件模板无效！");
                    } else {
                        xslt = this.getClass().getResource(xslt).getPath();
                        Map m = new HashMap();
                        m.put("rs", rs);
                        try {
                            File tmp = File.createTempFile(UUID.randomUUID().toString(), ".xls");
                            FileOutputStream out = new FileOutputStream(tmp);
                            ExcelUtils.export(xslt, m, out);
                            super.writeDataToClient(request, response, tmp, lhandle.getFileName());
                        } catch (Exception e) {
                            log.warn("处理导出文件出错！", e);
                            super.writeDataToClient(response, "配置的XLS导出文件模板无效！");
                        }
                    }
                } else {
                    log.warn("无效的处理返回值方式【" + __dsm__ + "】.");
                }
            } else {
                RecordSet<Record> rs = HSF.query(lhandle.getDbl(), sql, ps, cp);
                super.writeDataToClient(response, rs.toJson());
            }
        }
    }

    public AcFwd loadv(HttpServletRequest request, HttpServletResponse response) {
        if (checkPara(request, response)) {
            ///////////////////////////
            XForm xf = Conf.getXForm(_sid);
            XHandle lhandle = xf.getListHandle();
            SqlProc sp = new SqlProc(lhandle);
            String sql = sp.crtSql(null);
            ///////////////////////////
            RecordSet<Record> rs = HSF.query(lhandle.getDbl(), sql);
            if (rs.next()) {
                this.writeDataToClient(response, rs.getRecord().toString());
            } else {
                this.writeDataToClient(response, "{}");

            }
        }
        return null;
    }

    private String packSql(String sql, Map m, String para) {
        sql = sql.toUpperCase();
        if (TL.isNotEmpty(para)) {
            String x[] = para.split(","), p;
            for (String v : x) {
                p = (String) m.get(v.toUpperCase());
                sql = sql.replaceAll(":" + v.toUpperCase(), p);
            }
        }
        if (sql.contains("${SYSUSER.")) {
            RecordSet rs = (RecordSet) m.get("SYSUSER");
            if (rs != null) {
                Record c = rs.getRecord(1);
                Set<String> r = c.keySet();
                for (String e : r) {
                    if (sql.contains("${SYSUSER." + e.toUpperCase() + "}")) {
                        sql = sql.replaceAll("\\$\\{SYSUSER\\." + e.toUpperCase() + "\\}", c.getString(e));
                    }
                }
            }
        }
        return sql;
    }

    public AcFwd combobox(HttpServletRequest request, HttpServletResponse response) {
        if (checkPara(request, response)) {
            String type = Conf.getBaseProp(_sid, Conf.FORM._cb_type);
            if ("DB".equalsIgnoreCase(type)) {
                String para = Conf.getBaseProp(_sid, Conf.FORM._cb_para);
                String sql = Conf.getBaseProp(_sid, Conf.FORM._cb_db_sql);
                String dbl = Conf.getBaseProp(_sid, Conf.FORM._cb_dbl);
                String ll = request.getParameter("__defvp__");
                Map m = this.parsePara(request);
                {
                    m.put("__defvp__", ll);
                    if (TL.isEmpty(para)) {
                        para = "-";
                    }
                }
                String key = CacheProc.getCacheKeys(_sid, para + ",__defvp__", m);
                if (CacheProc.haveCacheData(key)) {
                    //缓存
                    this.writeDataToClient(response, CacheProc.cacheData(key));
                    log.debug("缓存命中...->KEY:" + key);
                } else {
                    sql = packSql(sql, m, para);
                    RecordSet<Record> rs = HSF.query(dbl, sql);
                    String rtn;
                    if (TL.isEmpty(ll) || !ll.matches("LST|FST")) {
                        rtn = rs.toString();
                    } else {
                        rtn = rs.toComboxString(ll);
                    }
                    log.info("缓存...->KEY:" + key + " -->" + _sid);
                    CacheProc.cacheData(key, rtn);
                    this.writeDataToClient(response, rtn);
                }
            } else if ("cfg".equalsIgnoreCase(type)) {
                String cfg = Conf.getBaseProp(_sid, Conf.FORM._cb_cfg);
                this.writeDataToClient(response, cfg);
            } else {
                this.writeDataToClient(response, "[]");
            }
        }
        return null;
    }

    public AcFwd xtree(HttpServletRequest request, HttpServletResponse response) {
        if (checkPara(request, response)) {
            XTreeBuzz xtb = new XTreeBuzz(_sid, this.parsePara(request));
            this.writeDataToClient(response, xtb.toJson());
        }
        return null;
    }

    public AcFwd xtable(HttpServletRequest request, HttpServletResponse response) {
        if (checkPara(request, response)) {
            System.out.println("...xtable");
        }
        return null;
    }
}
